import {
  Popconfirm,
  Space,
  TableColumnsType,
  Tooltip,
  Typography,
  Image,
  Badge,
  message,
  Input,
  Tag,
  Table,
} from 'antd'
import { NavigateFunction } from 'react-router-dom'
import type { ITableData, ProductSpuColorDetailVO } from './types'
import { STATUSBAND } from '@/constant'
import { getImageByUrl } from '@/utils/getImageByUrl'
import { ORDER_METTING_STATUS_TEXT } from '@/constant/goods'
import PermissionLink from '@/components/PermissionLink'
import {
  CheckOutlined,
  CloseOutlined,
  EditOutlined,
  PictureOutlined,
  QuestionCircleOutlined,
  StopOutlined,
} from '@ant-design/icons'
import { psdEditPicture } from '@/api/goods'
import { importBlobImg } from '@/api'
export const useIndexColumns = ({
  navigate,
  changeStatus,
  changeStatusConfirm,
  reLoadPage,
  editDevPicture,
  tableData,
  settableData,
  onSavePlan,
  isRoot,
}: {
  navigate: NavigateFunction
  changeStatus: (info: ProductSpuColorDetailVO, status: number) => void
  onSavePlan: (info: ITableData) => void
  changeStatusConfirm: (info: ITableData, item: ProductSpuColorDetailVO) => void
  reLoadPage: () => void
  editDevPicture: boolean
  isRoot: boolean
  tableData: ITableData[]
  settableData: React.Dispatch<React.SetStateAction<ITableData[]>>
}): TableColumnsType<ITableData> => [
  {
    title: '款式图',
    dataIndex: 'mainPicFileId',
    key: 'mainPicFileId',
    align: 'center',
    width: 150,
    fixed: 'left',
    render: (info, rows) => {
      return (
        <div className="image_hover_change_wrap">
          <div className="ihcw_image">
            {rows.isEdit ? (
              <div style={{ padding: '0 40px 0 0' }}>
                <Input
                  placeholder="粘贴图片到这里"
                  style={{ border: 'none', outline: 'none', boxShadow: 'none', borderRadius: 'none' }}
                  autoFocus
                  onPaste={async (event: any) => {
                    const items = (event.clipboardData || event.originalEvent.clipboardData).items
                    let hasImage = false
                    for (const item of items) {
                      if (item.type.indexOf('image') === 0) {
                        hasImage = true
                        const blob = item.getAsFile()
                        if (blob.size > 1024 * 1024 * 10) {
                          message.warning('图片大小不能超过10MB！')
                          return
                        }
                        const imgdata = await importBlobImg(blob)
                        if (imgdata.code === 200 && imgdata.data?.linkUrl) {
                          const paramsData = {
                            planingId: rows?.planingId || '',
                            spuDevId: rows?.spuDevId,
                            mainPicFileId: imgdata.data?.linkUrl,
                          }
                          const res = await psdEditPicture(paramsData)
                          if (res.code === 200) {
                            message.success('操作成功')
                            reLoadPage()
                          }
                        }
                      }
                    }
                    if (!hasImage) {
                      message.warning('上传失败，粘贴内容不是图片！')
                      rows.isEdit = !rows.isEdit
                      settableData([...tableData])
                    }
                  }}
                ></Input>
              </div>
            ) : (
              <Image
                rootClassName="table_image"
                width={50}
                height={50}
                src={info}
                fallback={getImageByUrl('moren.png')}
              />
            )}
          </div>
          {editDevPicture && (
            <div className="fly_btn_upload">
              <Tooltip title={rows.isEdit ? '取消' : '图片替换'}>
                <div
                  onClick={() => {
                    rows.isEdit = !rows.isEdit
                    settableData([...tableData])
                  }}
                >
                  {rows.isEdit ? <StopOutlined /> : <PictureOutlined />}
                </div>
              </Tooltip>
            </div>
          )}
        </div>
      )
    },
  },
  {
    title: '设计编码',
    dataIndex: 'designCode',
    key: 'designCode',
    align: 'center',
    width: 120,
    render: (info, rows) => {
      return (
        <div>
          <div>{info || '-'}</div>
          {!rows.planNo && <Tag color="processing">款式草稿</Tag>}
        </div>
      )
    },
  },
  {
    title: (
      <div>
        <div>创建日期</div>
        <div>更新日期</div>
      </div>
    ),
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    width: 160,
    render: (_, rows) => {
      return (
        <div>
          <div>{rows?.createTime || '-'}</div>
          <div>{rows?.updateTime || '-'}</div>
        </div>
      )
    },
  },
  {
    title: '款式编码',
    dataIndex: 'spuCode',
    key: 'spuCode',
    align: 'center',
    width: 120,
    ellipsis: {
      showTitle: false,
    },
    render: (info) => {
      return (
        <Tooltip placement="top" title={info}>
          {info || '-'}
        </Tooltip>
      )
    },
  },
  {
    title: '款式名称',
    dataIndex: 'spuName',
    key: 'spuName',
    align: 'center',
    width: 180,
    ellipsis: {
      showTitle: false,
    },
    render: (info, rows, index) => {
      return (
        <Tooltip placement="top" title={info}>
          <Typography.Link
            ellipsis
            onClick={() => {
              navigate('/goods/style/detail?spuDevId=' + rows.spuDevId)
            }}
            style={{ paddingLeft: 12, paddingRight: 12 }}
          >
            {info}
          </Typography.Link>
        </Tooltip>
      )
    },
  },
  {
    title: '厂家款号',
    dataIndex: 'factorySpuCode',
    key: 'factorySpuCode',
    align: 'center',
    width: 120,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '采购方式',
    dataIndex: 'purchaseType',
    key: 'purchaseType',
    align: 'center',
    width: 100,
    render: (info) => {
      return info == 0 ? '集采' : info == 1 ? '现采' : '-'
    },
  },
  {
    title: (
      <div>
        <div>商品企划编号</div>
        <div>开发季</div>
      </div>
    ),
    dataIndex: 'planNo',
    key: 'planNo',
    align: 'center',
    width: 160,
    render: (_, rows) => {
      return (
        <div>
          <div>
            {rows?.spuColorDetails?.some((item) => item.status == 3) ? (
              <Typography.Link
                ellipsis
                onClick={() => navigate('/goods/plan/detail?planingId=' + rows.planingId)}
                style={{ paddingLeft: 12, paddingRight: 12 }}
              >
                {rows.planNo}
              </Typography.Link>
            ) : !rows.rowsEdit ? (
              <div
                onClick={() => {
                  if (!rows.rowsEdit) {
                    rows.rowsEdit = true
                    settableData([...tableData])
                  }
                }}
              >
                {rows.planNo ? (
                  rows.planNo
                ) : (
                  <span style={{ color: 'var(--primary-color)', cursor: 'pointer' }}>点击关联企划</span>
                )}
                <Tooltip placement="top" title="关联企划坑位">
                  <EditOutlined style={{ color: 'var(--primary-color)', cursor: 'pointer', marginLeft: 4 }} />
                </Tooltip>
              </div>
            ) : (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Input
                  autoFocus
                  style={{ width: 60 }}
                  onChange={(event) => {
                    rows.newplanNo = event.target.value
                    settableData([...tableData])
                  }}
                ></Input>
                <Tooltip placement="top" title="保存">
                  <CheckOutlined
                    style={{ color: 'var(--primary-color)', cursor: 'pointer' }}
                    onClick={() => {
                      rows.rowsEdit = false
                      settableData([...tableData])
                      onSavePlan(rows)
                    }}
                  />
                </Tooltip>
                <Tooltip placement="top" title="取消">
                  <CloseOutlined
                    style={{ color: 'var(--primary-color)', cursor: 'pointer' }}
                    onClick={() => {
                      rows.rowsEdit = false
                      settableData([...tableData])
                    }}
                  />
                </Tooltip>
              </div>
            )}
          </div>
          <div>{rows.devSeasonName || '-'}</div>
        </div>
      )
    },
  },
  {
    title: '吊牌价',
    dataIndex: 'originSalePrice',
    key: 'originSalePrice',
    align: 'center',
    width: 120,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: (
      <div>
        <div>开发SKC数</div>
        <div>企划SKC数</div>
      </div>
    ),
    dataIndex: 'status',
    key: 'status',
    align: 'center',
    width: 120,
    render: (_, rows) => {
      return (
        <div>
          <div>{rows?.skcDevNum == 0 ? 0 : rows?.skcDevNum ? rows?.skcDevNum : '-'}</div>
          <div>{rows?.skcPlanNum == 0 ? 0 : rows?.skcPlanNum ? rows?.skcPlanNum : '-'}</div>
        </div>
      )
    },
  },
  {
    title: '主供应商',
    dataIndex: 'supplierName',
    key: 'supplierName',
    align: 'center',
    width: 180,
    ellipsis: {
      showTitle: false,
    },
    render: (info) => {
      return (
        <Tooltip placement="top" title={info}>
          {info || '-'}
        </Tooltip>
      )
    },
  },
  {
    title: '款式分类',
    dataIndex: 'configClassName',
    key: 'configClassName',
    align: 'center',
    width: 250,
    ellipsis: {
      showTitle: false,
    },
    render: (info) => {
      return (
        <Tooltip placement="top" title={info}>
          {info || '-'}
        </Tooltip>
      )
    },
  },
  {
    title: '关联报价单',
    dataIndex: 'firstMainSupplierQuotationOrderCode',
    key: 'firstMainSupplierQuotationOrderCode',
    align: 'center',
    width: 220,
    ellipsis: {
      showTitle: false,
    },
    render: (info, rows) => {
      return rows?.firstMainSupplierQuotationOrderVOList?.[0]?.quotationOrderCode ? (
        <Tooltip placement="top" title={info}>
          <Typography.Link
            ellipsis
            onClick={() => {
              navigate(
                '/goods/quotation/list?quotationOrderCode=' +
                  rows?.firstMainSupplierQuotationOrderVOList?.[0]?.quotationOrderCode,
              )
            }}
            style={{ paddingLeft: 12, paddingRight: 12, cursor: 'pointer' }}
          >
            {rows?.firstMainSupplierQuotationOrderVOList?.[0].quotationOrderCode || '-'}
          </Typography.Link>
        </Tooltip>
      ) : (
        '-'
      )
    },
  },
  {
    title: (
      <div>
        <div>最新议价</div>
        <div>当前毛利率</div>
      </div>
    ),
    dataIndex: 'negotiatePrice',
    key: 'negotiatePrice',
    align: 'center',
    width: 120,
    render: (_, rows) => {
      return rows?.firstMainSupplierQuotationOrderVOList && rows?.firstMainSupplierQuotationOrderVOList?.length > 0 ? (
        rows?.firstMainSupplierQuotationOrderVOList.length === 1 ? (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div>
              <div>{rows?.firstMainSupplierQuotationOrderVOList[0]?.negotiatePrice || '-'}</div>
              <div>
                {rows?.firstMainSupplierQuotationOrderVOList[0]?.negotiatePriceProfitRate
                  ? Number(rows?.firstMainSupplierQuotationOrderVOList[0]?.negotiatePriceProfitRate) + '%'
                  : '-'}
              </div>
            </div>
            {rows?.firstMainSupplierQuotationOrderVOList[0].priceErrorRemark && (
              <div style={{ marginLeft: 4, cursor: 'pointer' }}>
                <Tooltip
                  placement="top"
                  title={rows?.firstMainSupplierQuotationOrderVOList?.map((item, index) => {
                    return <div key={index}>{item?.priceErrorRemark || '-'}</div>
                  })}
                >
                  <QuestionCircleOutlined />
                </Tooltip>
              </div>
            )}
          </div>
        ) : (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Tooltip
              placement="top"
              color="#fff"
              overlayInnerStyle={{ width: 'max-content' }}
              title={
                <div className="small_sise_customtable">
                  <Table
                    bordered
                    pagination={false}
                    rowHoverable={false}
                    rowClassName={(_, index) => {
                      return index % 2 === 0 ? '' : 'zebra-row-odd'
                    }}
                    rowKey="quotationOrderId"
                    dataSource={rows?.firstMainSupplierQuotationOrderVOList || []}
                    columns={[
                      {
                        title: '颜色',
                        dataIndex: 'colorDetailName',
                        key: 'colorDetailName',
                        align: 'center',
                        width: 150,
                        render: (_, rows) => rows?.colorDetails?.map((it: any) => it?.colorDetailName).join('，'),
                      },
                      {
                        title: '最新议价',
                        dataIndex: 'negotiatePrice',
                        key: 'negotiatePrice',
                        align: 'center',
                        width: 150,
                        render: (info) => (info ? info : '-'),
                      },
                      {
                        title: '当前毛利率',
                        dataIndex: 'negotiatePriceProfitRate',
                        key: 'negotiatePriceProfitRate',
                        align: 'center',
                        width: 150,
                        render: (info) => Number(info || 0) + '%',
                      },
                    ]}
                  ></Table>
                </div>
              }
            >
              分色议价
            </Tooltip>
            {rows?.firstMainSupplierQuotationOrderVOList.some((item) => item?.priceErrorRemark) && (
              <Tooltip
                placement="top"
                title={rows?.firstMainSupplierQuotationOrderVOList?.map((item, index) => {
                  return (
                    <div key={index}>
                      {item?.colorDetails?.map((it: any) => it.colorDetailName).join('，')}：
                      {item?.priceErrorRemark || '-'}
                    </div>
                  )
                })}
              >
                <span style={{ marginLeft: 4, cursor: 'pointer' }}>
                  <QuestionCircleOutlined />
                </span>
              </Tooltip>
            )}
          </div>
        )
      ) : (
        '-'
      )
    },
  },
  // {
  //   title: '价格异常备注',
  //   dataIndex: 'priceErrorRemark',
  //   key: 'priceErrorRemark',
  //   align: 'center',
  //   width: 140,
  //   ellipsis: {
  //     showTitle: false,
  //   },
  //   render: (_, rows) => {
  //     return rows?.firstMainSupplierQuotationOrderVOList && rows?.firstMainSupplierQuotationOrderVOList?.length > 0 ? (
  //       rows?.firstMainSupplierQuotationOrderVOList.length === 1 ? (
  //         <Tooltip
  //           placement="topLeft"
  //           title={rows?.firstMainSupplierQuotationOrderVOList?.map((item, index) => {
  //             return <div key={index}>{item?.priceErrorRemark || '-'}</div>
  //           })}
  //         >
  //           {rows?.firstMainSupplierQuotationOrderVOList[0]?.priceErrorRemark || '-'}
  //         </Tooltip>
  //       ) : (
  //         <Tooltip
  //           placement="top"
  //           title={rows?.firstMainSupplierQuotationOrderVOList?.map((item, index) => {
  //             return (
  //               <div key={index}>
  //                 {item?.colorDetails?.map((it: any) => it.colorDetailName).join('，')}：{item?.priceErrorRemark || '-'}
  //               </div>
  //             )
  //           })}
  //         >
  //           分色价格异常备注
  //         </Tooltip>
  //       )
  //     ) : (
  //       '-'
  //     )
  //   },
  // },
  {
    title: '状态',
    dataIndex: 'enableStatus',
    key: 'enableStatus',
    align: 'center',
    width: 100,
    render: (info) => {
      return <Badge status={info == 1 ? 'success' : 'error'} text={STATUSBAND[info] || '-'} />
    },
  },
  {
    title: '款式',
    children: [
      {
        title: '图片',
        dataIndex: 'pic',
        key: 'pic',
        width: 100,
        align: 'center',
        render: (_, rows) => {
          return (
            rows?.spuColorDetails?.map((item) => {
              return (
                <div
                  key={item.colorDetailId + (item.colorCode || '') + item.spuColorDetailId}
                  className="border_bottom_nolast ant-table-cell-ellipsis"
                >
                  {item?.picUrl ? (
                    <img style={{ display: 'inline-block', width: 30, height: 30 }} src={item?.picUrl} />
                  ) : item.rgbValue ? (
                    <span
                      style={{
                        width: 30,
                        height: 30,
                        backgroundColor: `rgb${item.rgbValue}`,
                        display: 'inline-block',
                        verticalAlign: 'middle',
                      }}
                    ></span>
                  ) : (
                    '-'
                  )}
                </div>
              )
            }) || '-'
          )
        },
      },
      {
        title: '颜色编码',
        dataIndex: 'color',
        key: 'color',
        width: 100,
        align: 'center',
        render: (_, rows) => {
          return (
            rows?.spuColorDetails?.map((item) => {
              return (
                <div
                  className="border_bottom_nolast ant-table-cell-ellipsis"
                  key={item.colorDetailId + (item.colorCode || '') + item.spuColorDetailId}
                >
                  {item.colorCode || '-'}
                </div>
              )
            }) || '-'
          )
        },
      },
      {
        title: '颜色名称',
        dataIndex: 'colorName',
        key: 'colorName',
        width: 100,
        align: 'center',
        render: (_, rows) => {
          return (
            rows?.spuColorDetails?.map((item) => {
              return (
                <div
                  className="border_bottom_nolast ant-table-cell-ellipsis"
                  key={item.colorDetailId + (item.colorCode || '') + item.spuColorDetailId}
                >
                  {item.colorDetailName || '-'}
                </div>
              )
            }) || '-'
          )
        },
      },
      {
        title: '订货状态',
        dataIndex: 'orderstatus',
        key: 'orderstatus',
        width: 300,
        align: 'center',
        render: (_, rows) => {
          return rows?.spuColorDetails && rows?.spuColorDetails?.length > 0
            ? rows?.spuColorDetails?.map((item) => {
                return (
                  <div
                    className="border_bottom_nolast ant-table-cell-ellipsis"
                    key={item.colorDetailId + (item.colorCode || '') + item.spuColorDetailId}
                  >
                    <Space size={'middle'}>
                      <Typography.Text>{ORDER_METTING_STATUS_TEXT[item.status]}</Typography.Text>
                      {item.status == 1 ? (
                        <PermissionLink permission="confirmSelect" onClick={() => changeStatusConfirm(rows, item)}>
                          确认选中
                        </PermissionLink>
                      ) : null}
                      {item.status == 0 || item.status == 2 ? (
                        <Popconfirm
                          title={`确认上订货会吗？`}
                          onConfirm={() => changeStatus(item, 1)}
                          okText="确认"
                          cancelText="取消"
                        >
                          <PermissionLink permission="waitSelect">上订货会</PermissionLink>
                        </Popconfirm>
                      ) : null}
                      {item.status == 0 || item.status == 1 ? (
                        <Popconfirm
                          title={`确认未选中吗？`}
                          onConfirm={() => changeStatus(item, 2)}
                          okText="确认"
                          cancelText="取消"
                        >
                          <PermissionLink permission="rejectSelect">未选中</PermissionLink>
                        </Popconfirm>
                      ) : null}
                    </Space>
                  </div>
                )
              })
            : '-'
        },
      },
    ],
  },
]
